package y_2025.m11.d12;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    private final ReentrantLock lock = new ReentrantLock(); // 创建一个ReentrantLock实例

    private int count = 0; // 共享资源

    public void increment() {
        lock.lock(); // 获取锁

        try {
            // 在临界区中更新共享资源
            count++;
            // 调用使用同一个锁来保护共享资源的方法: getCount()
            System.out.println("Incremented count: " + getCount());
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    public int getCount() {
        lock.lock(); // 获取锁

        try {
            // 在临界区中访问共享资源
            return count;
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    public static void main(String[] args) {
        ReentrantLockExample example = new ReentrantLockExample();

        // 创建一个线程并启动
        Thread incrementThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                example.increment();
            }
        });
        incrementThread.start();

        // 等待线程执行完毕
        try {
            incrementThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 打印最终的计数值
        System.out.println("Final count: " + example.getCount());
    }
}
